﻿using System;
using System.Linq;
using System.Windows.Navigation;
using CuteRibs.MVVMLib;
using CuteRibs.WowArmory.Models;
using CuteRibs.WowArmory.Resources;

namespace CuteRibs.WowArmory.ViewModels
{
	public class RealmDetailPageViewModel : PageViewModelBase
	{
		public AppRes AppRes { get { return App.AppResource; } }
		public AppTitleControlViewModel AppTitle { get; set; }
		public Realm Realm { get; set; }

		public RealmDetailPageViewModel()
		{
			if (App.IsDesignMode)
			{
				this.SetRealm("Arygos");
			}
		}

		public override void OnNavigatedTo(ViewBase sender, NavigationEventArgs eventArgs, NavigationContext context)
		{
			base.OnNavigatedTo(sender, eventArgs, context);

			this.SetRealm(context.QueryString["Realm"]);
		}

		private void SetRealm(string realm)
		{
			Region region;

			if (App.IsDesignMode)
			{
				region = Region.Americas;
			}

			region = App.RegionData.Region;
			this.AppTitle = new AppTitleControlViewModel(AppRes.Title_Realms, region.DisplayName);
			this.GetRealm(region, realm);
		}

		private async void GetRealm(Region region, string realm)
		{
			this.ShowProgressBar = true;

			try
			{
				var realms = await WowClient.GetRealmStatus(region, realm);

				if (realms == null || realms.Length != 1)
				{
					App.ShowAlert(string.Format(AppRes.MsgCannotFindRealm, realm, region.Domain));
					this.ShowProgressBar = false;
					return;
				}

				this.Realm = realms.First();
			}
			catch (Exception ex)
			{
				App.ShowError(AppException.CreateRealmException(ex, region.Domain, realm));
			}

			this.ShowProgressBar = false;
		}
	}
}
